package org.example.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.example.model.LoginUser;

import java.util.Date;

@Slf4j
public class JwtUtil {

    //过期时间7天
    private static final long EXPIRE = 7 * 24 * 60 * 60 * 1000;

    //主题
    private static final String SUBJECT = "lin-subject";

    //令牌前缀
    private static final String PREFIX = "lin-prefix";

    //加密的密钥
    private static final String SECRET = "lin666";

    //生成token的方法
    public static String geneJwtToken(LoginUser loginUser) {
        if (loginUser == null) {
            throw new NullPointerException("loginUser为空");
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id", loginUser.getId())
                .claim("name", loginUser.getName())
                .claim("head_img", loginUser.getHeadImg())
                .claim("mail", loginUser.getMail())
                //发布时间
                .setIssuedAt(new Date())
                //过期时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //加密算法和密钥
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        token = PREFIX + token;
        return token;
    }

    //解密token
    public static Claims checkJwt(String token) {
        try {
            Claims claims = Jwts.parser()
                    //密钥
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(PREFIX, ""))
                    .getBody();
            return claims;
        } catch (Exception e) {
            log.info("jwt解密失败");
            return null;
        }
    }

}
